package com.enterprise.projectManager.service.implemention;

import com.enterprise.projectManager.dto.LoginRequest;
import com.enterprise.projectManager.dto.LoginResponse;
import com.enterprise.projectManager.dto.SignUpRequest;
import com.enterprise.projectManager.model.User;
import com.enterprise.projectManager.rope.UserRope;
import com.enterprise.projectManager.service.AccountService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Transactional
public class AccountServiceImpl implements AccountService {
    private final UserRope userRope;
    private final CountServiceImpl countService;
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        User user = userRope.findByAccount(loginRequest.getAccount()).get();
        if (user != null && user.getPassword() != null)
        {
            boolean isPasswordMatch = passwordEncoder.matches(loginRequest.getPassword(),user.getPassword());
            if (isPasswordMatch)
            {
                LoginResponse loginResponse =new LoginResponse();
                loginResponse.setAccount(user.getAccount());
                loginResponse.setUserId(user.getUserId());
                loginResponse.setUserName(user.getUsername());
                loginResponse.setRole(user.getRole());

                return loginResponse;
            }
        }
        return null;
    }

    @Override
    public User create(SignUpRequest signUpRequest) {
        User user =new User();
        user.setAccount(signUpRequest.getAccount());
        user.setUsername(signUpRequest.getUserName());
        user.setPassword(passwordEncoder.encode(signUpRequest.getPassword()));
        user.setUserId(countService.generalUserId());
        user.setRole(signUpRequest.getRole());
        return userRope.save(user);
    }

    @Override
    public Boolean isExistId(String userId) {
        if (userRope.existsById(userId)) return Boolean.TRUE;
        else return Boolean.FALSE;
    }

    @Override
    public Boolean isExistAccount(String account) {
        if (userRope.existsByAccount(account)) return Boolean.TRUE;
        else return Boolean.FALSE;
    }

    @Override
    public List<User> listAll() {
        return userRope.findAll();
    }


}
